#!/usr/bin/python
# -*- coding: utf8 -*-

from pymylib.lib.base import *
from pymylib.model import Session, Card, User, OrderHistory
from pymylib.lib.apihelper import *
from mako.lookup import TemplateLookup
from pylons.templating import render, render_response
from __init__ import perPage
from datetime import datetime

class OrderController(BaseController):
    template_prefix = '/card'
    
    def __before__(self):
        if 'user' in session:
            if session['user'] == 'anonymous':
                session['path_before_login'] = request.path_info
                session.save()
                return redirect_to(h.url_for(controller='login'))
        else: return redirect_to(h.url_for(controller='login'))

    def index(self):
        redirect_to(action='list')

    def list(self):
        c.pageTitle = unicode('Карточка заказов', encoding='utf8')
        c.formCaption = c.pageTitle
        c.curPage = 0

        #model.Card._connection.debug = True

        try:
            c.userID = int(request.params['id'])
            if c.userID == -1:
                c.userID = None
        except:
            c.userID = None


        card_q = Session.query(Card)
        try:
            c.curPage = int(request.params['pg'])-1            
            if (c.userID is not None):
                c.card = list(card_q.filter_by(id = c.userID)[perPage*c.curPage:perPage*(c.curPage+1)])
            else:
                c.card = list(card_q.all()[perPage*c.curPage:perPage*(c.curPage+1)])
        except:            
            if (c.userID is not None):                
                c.card = list(card_q.filter_by(id = c.userID).limit(perPage))
            else:                
                c.card = list(card_q.limit(perPage))


        ''' Получим страницы с диапазоном заданным perPage '''
        c.pages = []
        i = 0
        for cat in c.card[:int(card_q.count()/perPage)+1]:
            i = i+1
            c.pages.append(i)
        
        if len(c.pages) == 1:
            c.pages = None


        c.currentUser = None
        c.user_id = session['user_id']
        c.user_name = session['fio']

        user_q = Session.query(User)
        c.users = list(user_q.all())

        return render_response(self.template_prefix + '/list.myt')

    def add(self):        
        c.card = None

        return render_response(self.template_prefix + '/edit.myt')

    def create(self):
        """Insert object to datebase"""
        new_order = Card()
        
        new_order.biblio_id = int(request.params['biblio_id'])
        new_order.user_id = int(request.params['user_id'])

        if request.params['order_expiry_date'] == "": new_order.order_expiry_date = None
        else: new_order.order_expiry_date = request.params['order_expiry_date']
                
        new_order.order_date = datetime.now()
        
        try:                        
            Session.save(new_order)
            Session.commit()
        except:
            Session.rollback() 
            raise
        
        redirect_to('list')

    def __add_order_history__(self, biblioID, userID, orderDate):
        new_order_history = OrderHistory()

        new_order_history.biblio_id = biblioID
        new_order_history.user_id = userID
        new_order_history.order_date = orderDate
        new_order_history.close_order = datetime.now()
        
        try:                        
            Session.save(new_order_history)
            Session.commit()
        except:
            Session.rollback()
            raise
        
    def delete(self, id):
        card_q = Session.query(Card)
        card_obj = card_q.get_by(id=id)

        self.__add_order_history__(card_obj.biblio_id, card_obj.user_id, card_obj.order_date)

        try:
            Session.delete(card_obj)
            Session.commit()
        except:
            Session.rollback()
            raise

        redirect_to('../list')

    """
    SELECT user.id, user.fio, user.pasport, user.address, user.email,
        user.zip, user.phone, user.photo, user.user_name, user.password,
        user.permitions, user.note FROM user, card
        WHERE ((user.id = user.user_id) AND ((user.card_id = card.id)
            AND (card.id = 11)))
    """        
